package cn.piggy.gateway.core.socket;

import cn.piggy.gateway.core.config.ConfigHelper;
import cn.piggy.gateway.core.session.simple.SimpleGatewaySessionFactory;
import cn.piggy.gateway.core.socket.handler.AuthorizationHandler;
import cn.piggy.gateway.core.socket.handler.GatewayServerHandler;
import cn.piggy.gateway.core.socket.handler.RequestForwardHandler;
import cn.piggy.gateway.core.socket.handler.RequestLimitHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;


public class GatewayChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final ConfigHelper configHelper;
    private final SimpleGatewaySessionFactory gatewaySessionFactory;

    public GatewayChannelInitializer(ConfigHelper configHelper, SimpleGatewaySessionFactory gatewaySessionFactory) {
        this.configHelper = configHelper;
        this.gatewaySessionFactory = gatewaySessionFactory;
    }

    @Override
    protected void initChannel(SocketChannel channel) {
        ChannelPipeline line = channel.pipeline();
        line.addLast(new HttpRequestDecoder());
        line.addLast(new HttpResponseEncoder());
        line.addLast(new HttpObjectAggregator(1024 * 1024));
        line.addLast(new GatewayServerHandler(configHelper));
        line.addLast("limit", new RequestLimitHandler());
        line.addLast("auth", new AuthorizationHandler());
        line.addLast(new RequestForwardHandler(gatewaySessionFactory));
    }

}
